{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "529dded1",
   "metadata": {},
   "source": [
    "# 鉴权认证机制（获取access_token)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "0fc60d1d",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.13c1b1f7160c1dcc81c33579867dba94.315360000.1964435392.282335-25904781', 'expires_in': 2592000, 'session_key': '9mzdDtcyubcDtZJ0TnGOF53kh50joQS1PSBHmf/KpR28WI9/N00dI6I1vkpjkNCFpnKuVLqtUdnGFkE8/l3oOQL0UMD6nQ==', 'access_token': '24.5e0588b15f55d6d937f52f5e6f910ab7.2592000.1651667392.282335-25904781', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '81a701ef804cfbe281d110c8343f8f85'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=CB24XR0H2NW8VuGw1LqAjmjE&client_secret=GAfFYdoBLSllq0xBx1GhMj4LbYGMajXz'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "fba93206",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.da5581a879dae3fb76bbbafdb99f6e5a.315360000.1964435394.282335-25904781', 'expires_in': 2592000, 'session_key': '9mzdXUXNiZbFrK3Mxnfoh9JDQfHCMfO8ckOu22I2SNmYI2slkQqlRM/guvHAZeOLbWhZo6F7Ve9F3ThO0R34y1LZBnPg1Q==', 'access_token': '24.f105d3636dfba31d3964904fff69358c.2592000.1651667394.282335-25904781', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '050cab1fbc53ca4c67c84f9805891407'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'CB24XR0H2NW8VuGw1LqAjmjE',\n",
    "    'client_secret':'GAfFYdoBLSllq0xBx1GhMj4LbYGMajXz'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "1b8e5e44",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.f105d3636dfba31d3964904fff69358c.2592000.1651667394.282335-25904781'"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token = response.json()['access_token']\n",
    "access_token"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1df2bf05",
   "metadata": {},
   "source": [
    "## 通用物体和场景识别\n",
    "\n",
    "* 接口描述\n",
    "> 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "\n",
    "* 请求示例\n",
    "> HTTP 方法：POST\n",
    "\n",
    "* 请求URL\n",
    "> https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\n",
    "\n",
    "* 鉴权认证机制(access_token)\n",
    "* 获取Access Token\n",
    "* 获取access_token示例代码:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "9b6a7693",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "2c39d6cc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 图像识别 url ： https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c718eeb7",
   "metadata": {},
   "source": [
    "* 示例代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "ee7f5d5a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '贾斯汀·比伯', 'score': 0.801283, 'root': '公众人物'}, {'keyword': '人物特写', 'score': 0.630983, 'root': '人物-人物特写'}, {'keyword': '屏幕截图', 'score': 0.459409, 'root': '非自然图像-屏幕截图'}, {'keyword': '美女', 'score': 0.292357, 'root': '人物-人物特写'}, {'keyword': '时装T台', 'score': 0.125268, 'root': '人物-人物特写'}], 'log_id': 1510958904415511318}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('jiast.jpg', 'rb') #绝对路径的读取\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = access_token\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30e65603",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "ff4de34a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '彭于晏', 'score': 0.742524, 'root': '公众人物', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%BD%AD%E4%BA%8E%E6%99%8F/305410', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b8389b504fc2d5624bbe5517ef1190ef77c66c92', 'description': '彭于晏，1982年3月24日出生于台湾省澎湖县，毕业于不列颠哥伦比亚大学，影视男演员、歌手。2002年，因出演个人首部电视剧《爱情白皮书》 ，从而进入演艺圈。2005年，因在仙侠剧《仙剑奇侠传》中饰演唐钰一角而受到关注。2006年，主演剧情片《六号出口》。2007年，凭借爱情片《基因决定我爱你》提名第44届台湾电影金马奖最佳新演员，并为金马短片单元制作片头，完成了个人导演处女作。2009年，发行个人首张EP《非爱不可》。2011年，彭于晏凭借励志片《翻滚吧！阿信》提名第48届台湾电影金马奖最佳男主角。2012年凭借动作片《激战》提名第50届台湾电影金马奖及第33届香港电影金像奖最佳男配角。2014年凭借主演的动作片《黄飞鸿之英雄有梦》提名第34届香港电影金像奖最佳男主角；同年，其主演的校园爱情电影《匆匆那年》在中国内地总票房为5.86亿人民币。2015年，主演青春片《破风》。2016年，主演的动作警匪片《湄公河行动》票房突破10亿人民币；同年，主演电影《寒战2》。2018年7月13日，主演的动作喜剧电影《邪不压正》上映；12月，彭于晏担任野生救援公益大使。2020年，主演的动作剧情电影《紧急救援》上映；10月30日，参演的纪录片《海龟奇“援”》发布。2021年，主演的犯罪剧情电影《热带往事》上映；10月参演的电影《第一炉香》上映。'}}, {'keyword': '美女', 'score': 0.533284, 'root': '人物-人物特写', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BE%8E%E5%A5%B3/109596', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/91529822720e0cf3acdfc0280046f21fbe09aa3d', 'description': '美女，汉语词语，拼音是měi nǚ，意思是容貌姣好、仪态优雅的女子。'}}, {'keyword': '男孩', 'score': 0.351643, 'root': '人物活动-人物特写', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%94%B7%E5%AD%A9/20490172', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/7dd98d1001e93901213f8c0354a543e736d12f2e38ff', 'description': '《男孩》是由梁博填词、谱曲、编曲并演唱的一首音乐单曲。该音乐单曲由梁博于2017年3月25日在湖南卫视文化娱乐类节目《歌手2017》第10期中首次演唱。'}}, {'keyword': '歌唱家', 'score': 0.190326, 'root': '人物活动-文艺活动', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%AD%8C%E5%94%B1%E5%AE%B6/6461176', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/241f95cad1c8a786d75fe6026409c93d70cf5040', 'description': '歌唱家，即歌唱艺术大家，是指具有精湛的歌唱水平，深厚的艺术水准，高尚的道德修养，并深受广大人民群众爱戴与欢迎的歌者。英文单词Singer 可以翻译为歌唱家，也可以翻译为歌手，两者是一个说法。一个优秀的歌唱家必定拥有给人灵魂震撼，引起人们共鸣，有思想深度的歌曲作品，从而引起人们的印象深刻。树立歌唱者在听众心目中的良好艺术形象和风格形象，用美好的音乐鼓舞人心，感动社会，并且感动世界。'}}, {'keyword': '人物特写', 'score': 0.021647, 'root': '人物-人物特写', 'baike_info': {}}], 'log_id': 1510958408068349338}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('D:yuyan.jpeg', 'rb') #绝对路径的读取\n",
    "# f = open('jiast.jpg', 'rb') # 相对路径  rb:read bytes 读取二进制文件格式\n",
    "\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b27145d",
   "metadata": {},
   "source": [
    "## 菜品识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "d8595ea1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '141', 'has_calorie': True, 'name': '牛肉丸', 'probability': '0.533697', 'baike_info': {}}, {'calorie': '248', 'has_calorie': True, 'name': '撒尿牛丸', 'probability': '0.225066', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%92%92%E5%B0%BF%E7%89%9B%E4%B8%B8/1352125', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/4e4a20a4462309f79052c326ba441bf3d7ca7bcb78e6', 'description': '撒尿牛丸是有着悠久历史的传统名菜，起源于清朝顺治年间的江南古镇松江，由王氏家族经过特殊工艺和配方精心研制而成，后因王家后人辗转到香港，逐渐成为港岛名吃。流传近二百年，风靡港台东南亚，倾倒无数食客。鸦片战争时期，港式牛丸流传到国外，当年周星驰在《食神》里用牛丸当乒乓球打的场面正是描述它的特点。甚至英国维多利亚女王竟将该美食御封为“贡丸”。'}}, {'calorie': '141', 'has_calorie': True, 'name': '牛筋丸', 'probability': '0.0849048', 'baike_info': {}}, {'calorie': '225', 'has_calorie': True, 'name': '丸子', 'probability': '0.0615739', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E4%B8%B8%E5%AD%90/2713374', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b7003af33a87e950e5564a7012385343fbf2b46d', 'description': '丸子是一种油炸/水煮食品，在世界各地都有出现，一般是用面团里面包上肉末、香菜等作料(也有用鱼肉、牛羊肉)，然后将油烧开，将包好的丸子放入油锅里炸一段时间，用笊篱捞出放在干燥的地方待冷却后即可食用。丸子饱满多汁，肉香嫩滑，是百姓的理想食品。'}}, {'calorie': '128', 'has_calorie': True, 'name': '墨鱼丸', 'probability': '0.0338712', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%A2%A8%E9%B1%BC%E4%B8%B8/6390524', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/0b46f21fbe096b63b27c9e4401338744ebf8acb9', 'description': '墨鱼丸色泽洁白，富有弹性，入口爽脆，味道鲜美，宴席菜和家常菜均可适用。墨鱼丸是海南和潮汕地区传统名菜。潮汕人常称为墨斗丸。用新鲜墨鱼和猪肥肉配制而成。曾在海南及全国烹饪大赛中获奖。'}}], 'log_id': 1510960477447043396}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('niurouwan.jpeg', 'rb') #绝对路径的读取\n",
    "# f = open('jiast.jpg', 'rb') # 相对路径  rb:read bytes 读取二进制文件格式\n",
    "\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dba3405a",
   "metadata": {},
   "source": [
    "### 看成品\n",
    "微信小程序搜索：识相Insight"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
